import { openUrl } from "./chrome";
import { Fetch, FetchPack, FETCH_EVENT_TYPE, SSE_EVENT_TYPE } from "./Fetch";
import logger from "./logger";
import { addMessageListener, MessageType, MessageTypeSub, sendMessage } from "./message"

type InitItem = [
    scope: RunScope | RunScope[],
    execute: () => void
]
const init = (items: InitItem[]) => {
    for (let i = 0; i < items.length; i++) {
        const [scope, execute] = items[i];
        const scopes: RunScope[] = [].concat(scope)
        if (scopes.includes(__SCOPE__)) {
            execute()
        }
    }
}

/** 添加prefixClass, content 需要额外处理 */
const __prefix__: InitItem[] = [
    [[RunScope.Main, RunScope.Popup], () => document.documentElement.classList.add(__CONFIG__.prefixClass)]
]

/** background 打开页面功能, 需要传递当前tab接收并处理 */
const __open__: InitItem[] = [
    [RunScope.Background, () => {
        globalThis.open = function (url?: string) {
            openUrl(url)
            return null
        }
    }]
]

/** 热更新功能， content 有跨域限制，需要监听来自background的消息 */
const __livereload__: InitItem[] = !__CONFIG__.DEV_SERVER ? [] : [
    [RunScope.Popup, () => {
        new EventSource(new URL('/listen', __CONFIG__.DEV_SERVER)).addEventListener('message', function (e) {
            if (e.data === '"true"') {
                location.reload()
            }
        })
    }],
    [RunScope.Background, () => {
        new EventSource(new URL('/listen', __CONFIG__.DEV_SERVER)).addEventListener('message', function (e) {
            if (e.data === '"true"') {
                sendMessage(MessageType.RELOAD)
            }
        })
    }],
    [[RunScope.Content, RunScope.Main, RunScope.Popup], () => {
        addMessageListener(MessageType.RELOAD, () => location.reload())
    }]
]

/** content端跨域fetch请求构建 */
const __fetch__: InitItem[] = [
    [[RunScope.Background], () => {
        addMessageListener<FetchPack<object>>(MessageType.FETCH, function (msg) {
            const { href, data, init, raw } = msg.data
            Fetch(href, data, init, raw).then(res => {
                sendMessage({
                    ...msg, data: res,
                })
            })
        })
    }],
    [RunScope.Content, () => {
        addMessageListener(MessageType.FETCH, function (msg) {
            dispatchEvent(new CustomEvent(FETCH_EVENT_TYPE + msg.uuid, { detail: msg.data }))
        })
    }],
]

/** content端SSE请求构建 */
const __sse__: InitItem[] = [
    [[RunScope.Background], () => {
        addMessageListener<string>(MessageType.SSE, function (msg) {
            logger.debug('background 接收到 SSE', msg.data, msg.uuid, __SCOPE__)
            const eventSource = new EventSource(msg.data)
            eventSource.onopen = function () {
                sendMessage({
                   ...msg, subType: MessageTypeSub.SSE_OPEN,
                }) 
            }
            eventSource.onmessage = function (e) {
                sendMessage({
                    ...msg, subType: MessageTypeSub.SSE_MESSAGE, data: e.data,
                })
            }
            eventSource.onerror = function (e) {
                sendMessage({
                    ...msg, subType: MessageTypeSub.SSE_ERROR, data: e,
                })
            }
            eventSource.close = function () {
                sendMessage({
                    ...msg, subType: MessageTypeSub.SSE_CLOSE,
                })
            }
        })
    }],
    [RunScope.Content, () => {
        addMessageListener(MessageType.SSE, function (msg) {
            dispatchEvent(new CustomEvent(SSE_EVENT_TYPE + msg.uuid, { detail: msg }))
        })
    }]
]
/** 打印dev环境信息 */
const __dev__: InitItem[] = [
    [[RunScope.Background, RunScope.Content, RunScope.Main, RunScope.Popup], () => {
        addMessageListener(function (msg) {
            logger.debug(new Date().toLocaleTimeString(), __SCOPE__, 'recive:', msg)
        })
    }]
]

export const global_init = function () {
    init(__prefix__)
    init(__open__)
    init(__livereload__)
    init(__fetch__)
    init(__sse__)
    init(__dev__)
}